//
//  HYManageAddressViewController.m
//  Guji
//
//  Created by 华谕 on 2017/9/6.
//  Copyright © 2017年 LXF. All rights reserved.
//

#import "HYManageAddressViewController.h"
//#import "HYAddressModel.h"
#import "HYNewAddressViewController.h"

static NSString *cellPath = @"addresscell";
@interface HYManageAddressViewController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong)UITableView *tableview;
@property (nonatomic, strong)NSArray *addressAry;

@end

@implementation HYManageAddressViewController

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [self requestAddressLise];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self creatUI];
}

- (void)creatUI
{
    self.view.backgroundColor = [UIColor whiteColor];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationItem.title = @"地址管理";
    CGFloat HeightX = 0;
    if (SCREEN_HEIGHT == 812)
    {
        HeightX = 34*displayheight;
    }
    self.tableview = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT-STA_NAV_HEIGHT-80*displaywidth-HeightX) style:UITableViewStylePlain];
    _tableview.delegate = self;
    _tableview.dataSource = self;
    _tableview.backgroundColor = RGB(248, 248, 248);
    _tableview.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableview];
    
    UIButton *addBtn = [ZCControl createButtonWithFrame:CGRectMake(60*displaywidth , SCREEN_HEIGHT-STA_NAV_HEIGHT-60*displaywidth-HeightX, SCREEN_WIDTH-120*displaywidth, 40*displaywidth) ImageName:nil Target:self Action:@selector(addBtnAct) Title:@"添加新地址" Font:15.0];
    [addBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    addBtn.backgroundColor = ThemeColor;
    [addBtn.layer setMasksToBounds:YES];
    [addBtn.layer setCornerRadius:5*displaywidth];
    [self.view addSubview:addBtn];
    
    
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _addressAry.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
    if (!cell)
    {
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellPath];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    if (_addressAry.count > 0)
    {
        HYAddressModel *model = _addressAry[indexPath.row];
        UILabel *titLab = [ZCControl createLabelWithFrame:CGRectMake(25*displaywidth, 0, 70*displaywidth, 45*displaywidth) Font:14.0 Text:model.linkman Color:RGB(77, 77, 77)];
//        titLab.text = [titLab.text stringByReplacingOccurrencesOfString:@"(null)" withString:@""];
        [cell.contentView addSubview:titLab];
        UILabel *phoneLab = [ZCControl createLabelWithFrame:CGRectMake(100*displaywidth, 0, 160*displaywidth, 45*displaywidth) Font:14.0 Text:model.linkPhone Color:RGB(77, 77, 77)];
        [cell.contentView addSubview:phoneLab];
        UIButton *edtBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-90*displaywidth, 12.5*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"bianji" Target:self Action:@selector(edtBtnAction:) Title:nil Font:11.0];
        edtBtn.backgroundColor = [UIColor clearColor];
        edtBtn.tag = indexPath.row + 100;
        [cell.contentView addSubview:edtBtn];
        UIButton *delectedBtn = [ZCControl createButtonWithFrame:CGRectMake(SCREEN_WIDTH-45*displaywidth, 12.5*displaywidth, 20*displaywidth, 20*displaywidth) ImageName:@"shanchu" Target:self Action:@selector(delectedBtnAction:) Title:nil Font:11.0];
        delectedBtn.backgroundColor = [UIColor clearColor];
        delectedBtn.tag = indexPath.row + 2100;
        [cell.contentView addSubview:delectedBtn];
//        if (!_isFromOrder)
//        {
//            UIImageView *imgView = [ZCControl createImageViewWithFrame:CGRectMake(SCREEN_WIDTH-30*displaywidth, 22.5*displayheight, 15*displayheight, 15*displayheight) ImageName:@"editor"];
//            [cell.contentView addSubview:imgView];
//        }
        CGFloat W = 100*displaywidth;
        if ([model.isDefault integerValue] == 1)
        {
            UILabel *defaLab = [ZCControl createLabelWithFrame:CGRectMake(25*displaywidth, 55*displaywidth, 50*displaywidth, 20*displaywidth) Font:12.0 Text:@"默认" Color:[UIColor whiteColor]];
            defaLab.textAlignment = NSTextAlignmentCenter;
            defaLab.backgroundColor = ThemeColor;
            defaLab.layer.cornerRadius = 5*displaywidth;
            defaLab.layer.masksToBounds = YES;
            [cell.contentView addSubview:defaLab];
        }
        else
        {
            UIButton *defaBtn = [ZCControl createButtonWithFrame:CGRectMake(25*displaywidth, 55*displaywidth, 100*displaywidth, 20*displaywidth) ImageName:@"danxuankuang" Target:self Action:@selector(setDefaAction:) Title:@" 设为默认" Font:12.0];
            [defaBtn setTitleColor:RGB(77, 77, 77) forState:UIControlStateNormal];
            defaBtn.backgroundColor = [UIColor clearColor];
            defaBtn.tag = indexPath.row + 4100;
            defaBtn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            defaBtn.contentVerticalAlignment = UIControlContentVerticalAlignmentCenter;
            [cell.contentView addSubview:defaBtn];
            W = 110*displaywidth;
        }
        UILabel *addressLab = [ZCControl createLabelWithFrame:CGRectMake(W, 50*displaywidth, 160*displaywidth, 30*displaywidth) Font:14.0 Text:[NSString stringWithFormat:@"%@%@%@%@",model.provinceText,model.cityText,model.districtText,model.detailAddress] Color:RGB(77, 77, 77)];
        [cell.contentView addSubview:addressLab];
        UIView *lineViews = [[UIView alloc] initWithFrame:CGRectMake(0, 89*displaywidth, SCREEN_WIDTH, 1*displaywidth)];
        lineViews.backgroundColor = LinesColor;
        [cell.contentView addSubview:lineViews];
    }
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (_isFromOrder)
    {
        HYAddressModel *model = _addressAry[indexPath.row];
        if (self.addressBlock != nil)
        {
            self.addressBlock(model);
            [self.navigationController popViewControllerAnimated:YES];
        }
    }
   
}

- (void)setDefaAction:(UIButton *)btn
{
    NSInteger index = btn.tag-4100;
    HYAddressModel *model = _addressAry[index];
    NSString *idStr = [NSString stringWithFormat:@"%@",model.ID];
    [self requestAddresssetDefault:idStr];
}

- (void)edtBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-100;
    HYAddressModel *model = _addressAry[index];
    HYNewAddressViewController *Vc = [[HYNewAddressViewController alloc] init];
    Vc.titStr = @"修改地址";
    Vc.isEdit = YES;
    Vc.addmodel = model;
    [self.navigationController pushViewController:Vc animated:YES];
}

- (void)delectedBtnAction:(UIButton *)btn
{
    NSInteger index = btn.tag-2100;
    HYAddressModel *model = _addressAry[index];
    WEAKSELF;
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"删除后，将清空该地址信息" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"删除" style:UIAlertActionStyleDestructive handler:^(UIAlertAction * _Nonnull action) {
        NSDictionary *dic = @{@"id":[NSString stringWithFormat:@"%@",model.ID]};
        [HYBaseHandler requestAddressDeleteParmers:dic Success:^(id obj) {
            if ([obj server_Getcodecheck])
            {
                [LTools showMBProgressWithText:@"删除成功" addToView:weakSelf.view];
                [weakSelf requestAddressLise];
            }
            else
            {
                [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
            }
            
        } failed:^(NSError *error) {
            
        }];
    }];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    [alertVC addAction:okAction];
    [alertVC addAction:cancelAction];
    [self presentViewController:alertVC animated:YES completion:nil];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90*displayheight;
}

//新增地址
- (void)addBtnAct
{
    HYNewAddressViewController *Vc = [[HYNewAddressViewController alloc] init];
    Vc.titStr = @"新增地址";
    [self.navigationController pushViewController:Vc animated:YES];
}

- (void)requestAddressLise
{
    WEAKSELF;
    [HYBaseHandler requestAddressListParmers:nil Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            _addressAry = [HYAddressModel mj_objectArrayWithKeyValuesArray:obj[@"data"]];
            dispatch_async(dispatch_get_main_queue(), ^{
                [weakSelf.tableview reloadData];
            });
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {

    }];
}

- (void)requestAddresssetDefault:(NSString *)addressID
{
    WEAKSELF;
    NSDictionary *dic = @{@"id":addressID};
    [HYBaseHandler requestAddresssetDefaultParmers:dic Success:^(id obj) {
        if ([obj server_Getcodecheck])
        {
            [weakSelf requestAddressLise];
        }
        else
        {
            [LTools showMBProgressWithText:obj[@"msg"] addToView:weakSelf.view];
        }
    } failed:^(NSError *error) {
        
    }];
}


- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
